package com.huafeng.service.impl;

import com.huafeng.model.entity.SysUser;
import com.huafeng.model.entity.SysUserRole;
import com.huafeng.security.CustomUser;
import com.huafeng.service.SysMenuService;
import com.huafeng.service.SysUserRoleService;
import com.huafeng.service.SysUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/20 18:35
 * @Description 自定义UserDetailsService实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.query().eq("username", username).one();
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUser.getStatus() == 0) {
            throw new RuntimeException("账号已停用");
        }

        // 获取用户拥有的角色
        List<SysUserRole> sysUserRoles = sysUserRoleService.query().eq("user_id", sysUser.getId()).list();
        // 用户拥有的角色id
        List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        // 获取用户权限
        List<String> userPermsList = sysMenuService.findUserPermsList(roleIds);
        List<SimpleGrantedAuthority> authorities = userPermsList.stream().filter(Objects::nonNull).map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new CustomUser(sysUser,authorities);
    }
}
